'''
@Project ：python-learn 
@File    ：5.1.py
@IDE     ：PyCharm 
@Author  ：计科2011-12-匡鑫
@Date    ：2024/9/20 10:49 
'''
import urllib.request
import re
import os

def download_images(url, num_images=1):
    # 尝试打开URL
    try:
        with urllib.request.urlopen(url) as response:
            html = response.read().decode('utf-8')
    except urllib.error.URLError as e:
        print(f"无法访问 {url}，尝试备用URL...")
        # 尝试备用URL
        url = 'https://www.nipic.com/topic/show_27313_1.html'
        with urllib.request.urlopen(url) as response:
            html = response.read().decode('utf-8')
            # 使用正则表达式查找图片链接
    image_urls = re.findall(r'src="([^"]+\.(jpg|jpeg|png|gif))"', html)
    # 确保有足够数量的图片可以下载
    if len(image_urls) < num_images:
        num_images = len(image_urls)
        print(f"只找到 {num_images} 张图片，将下载这些图片。")
        # 创建一个本地文件夹来保存图片
    folder_name = os.path.join(os.getcwd(), 'images')
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)
        # 下载图片
    for i, image_url in enumerate(image_urls[:num_images]):
        # 构建完整的图片URL（如果URL是相对路径）
        #https://www.tute.edu.cn+/+图片相对路径
            image_url = url.rsplit('/', 2)[0] + '/' + image_url[0].split('/',1)[-1]
            print(image_url)

                # 下载图片并保存到本地
            file_name = os.path.join(folder_name, f'image_{i + 1}.jpg')
            with urllib.request.urlopen(image_url) as image_response, open(file_name, 'wb') as f:
                f.write(image_response.read())
            print(f'已下载图片: {file_name}')

download_images('https://www.tute.edu.cn/xysh/yxtzsd.htm', 10)